package com.syyo.gulimall.product.utils;


import com.syyo.gulimall.product.domain.entity.CategoryEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: wangzhong
 * @Date: 2019/9/12 15:21
 * @Description: 树形结构
 */
public class TreeUtils {


    /**
     * 分类列表转换成树形结构
     *
     * @param list
     * @return
     */
    public static List<CategoryEntity> listToCategoryTree(List<CategoryEntity> list) {
        //用递归找子。
        List<CategoryEntity> treeList = new ArrayList<CategoryEntity>();
        for (CategoryEntity tree : list) {
            if (tree.getParentCid() == 0) {
                treeList.add(findChildren(tree, list));
            }
        }
        return treeList;
    }

    //寻找子节点
    private static CategoryEntity findChildren(CategoryEntity tree, List<CategoryEntity> list) {
        for (CategoryEntity node : list) {
            if (node.getParentCid().equals(tree.getCatId())) {
                if (tree.getChildren() == null) {
                    tree.setChildren(new ArrayList<CategoryEntity>());
                }
                tree.getChildren().add(findChildren(node, list));
            }
        }
        return tree;
    }
}
